import {Component, HostBinding, OnInit} from '@angular/core';
import {FormBuilder, Validators} from '@angular/forms';
import {MatDialog, MatSnackBar} from '@angular/material';
import {CaptchaComponent} from '../captcha.component';
import {ConfigService} from '../../../service/config.service';
import {AuthService} from '../../../service/auth.service';
import {UserService} from '../../../service/user.service';
import {alertDialog, loadingDialog} from '../../../util/dialog.util';
import {errorSnackBar, openSnackBar} from '../../../util/snack.util';
import {slideToTop} from '../../../anim/router.anim';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  animations: [slideToTop]
})
export class LoginComponent extends CaptchaComponent implements OnInit {
  @HostBinding('@routeAnim') routeAnim;
  hide = true;
  activationCode: string;

  constructor(private fb: FormBuilder, private routerInfo: ActivatedRoute,
              public snackBar: MatSnackBar, private dialog: MatDialog,
              public configService: ConfigService, public authService: AuthService, private userService: UserService) {
    super(snackBar, configService, authService);
    this.formModel = fb.group({
      email: ['', [Validators.required, Validators.email,
        Validators.minLength(6), Validators.maxLength(255)]],
      password: ['', [Validators.required,
        Validators.minLength(6), Validators.maxLength(32)]],
      captcha: ['', [Validators.required]]
    });
  }

  ngOnInit() {
    this.changeCaptcha();
    this.activationCode = this.routerInfo.snapshot.queryParams.code;
    if (this.activationCode) {
      // 发送激活用户请求
      this.authService.activateUser(this.activationCode).subscribe((result) => {
        alertDialog(this.dialog, '成功', '激活成功，开始登陆吧！');
      }, error1 => {
        errorSnackBar(this.snackBar, error1);
      });
    }
  }

  onSubmit() {
    if (this.formModel.valid) {
      const loadingDialogRef = loadingDialog(this.dialog);
      this.authService.login(
        this.formModel.get('email').value,
        this.formModel.get('password').value,
        this.formModel.get('captcha').value).subscribe((user) => {
        loadingDialogRef.close();
        this.userService.userChangeEvent.emit(user);
      }, error1 => {
        loadingDialogRef.close();
        errorSnackBar(this.snackBar, error1);
        this.changeCaptcha();
      });
    } else {
      openSnackBar(this.snackBar, '请检查是否符合所有填写规则');
    }
  }
}
